<?php

namespace App\Http\Controllers\Business;

use App\Common\Traits\Model\ModelSearchTrait;
use App\Http\Controllers\Controller;
use App\Models\Business\ShopProfileTemplate;
use Illuminate\Http\Request;

class ShopProfileTemplateController extends Controller
{
    use ModelSearchTrait;

    //
    public function index(Request $request,ShopProfileTemplate $profileTemplate)
    {
        $profileTemplate=$this->singleModelSearch($request,$profileTemplate,$this->serviceCondition());
        $templates=$profileTemplate->orderByDesc('updated_at')->paginate($request->size??20)->withQueryString();
        return $this->success($templates);
    }
    //
    public function serviceCondition()
    {
        return [
            ['template_name','like'],
        ];
    }

    //
    public function store(Request $request)
    {
        if(!$request->filled('template_name') || !$request->filled('template_content')){
            return $this->failed('模板名称和模板信息都不能为空',201);
        }
        $data=[
            'template_name'=>mb_substr($request->template_name,0,64),
            'template_content'=>$request->template_content,
        ];
        ShopProfileTemplate::create($data);
        return $this->success(['msg'=>'创建成功']);
    }


    //
    public function show(Request $request)
    {
        $show=ShopProfileTemplate::find($request->template_id??0);
        return $this->success($show);
    }

    //
    public function update(Request $request,ShopProfileTemplate $profileTemplate)
    {
        if(!$request->filled('template_name') || !$request->filled('template_content')){
            return $this->failed('模板名称和模板信息都不能为空',201);
        }
        $template=$profileTemplate->find($request->template_id??0);
        if(empty($template)){
            return $this->failed('id错误，无此模板',201);
        }
        $data=[
            'template_name'=>$request->template_name,
            'template_content'=>$request->template_content,
        ];
        $template->update($data);
        return $this->success(['msg'=>'编辑成功']);
    }

    //
    public function destroy(Request $request,ShopProfileTemplate $profileTemplate)
    {
        $template=$profileTemplate->find($request->template_id??0);
        if(empty($template)){
            return $this->failed('id错误，无此模板',201);
        }
        $template->delete();
        return $this->success(['msg'=>'删除成功']);
    }

    //
    public function getAllTemplates(){
        $templates=ShopProfileTemplate::all();
        return $this->success($templates);
    }

}
